apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: d8hostprocesses
  labels:
    heritage: deckhouse
    module: admission-policy-engine
    security.deckhouse.io: security-policy
  annotations:
    metadata.gatekeeper.sh/title: "Host Processes"
    metadata.gatekeeper.sh/version: 1.0.0
    description: >-
      Disallows sharing of host PID and/or IPC namespaces by pod containers.
      Corresponds to the `hostPID` and `hostIPC` fields in a PodSecurityPolicy.
      For more information, see
      https://kubernetes.io/docs/concepts/policy/pod-security-policy/#host-namespaces
spec:
  crd:
    spec:
      names:
        kind: D8HostProcesses
      validation:
        # Schema for the `parameters` field
        openAPIV3Schema:
          type: object
          description: >-
            Disallows sharing of host PID and/or IPC namespaces by pod containers.
            Corresponds to the `hostPID` and `hostIPC` fields in a PodSecurityPolicy.
            For more information, see
            https://kubernetes.io/docs/concepts/policy/pod-security-policy/#host-namespaces
          properties:
            allowHostPID:
              type: boolean
              description: "Allowed access to host PID namespacse."
            allowHostIPC:
              type: boolean
              description: "Allowed access to host IPC namespacse."
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package d8.security_policies

        violation[{"msg": msg, "details": {}}] {
          fields := ["hostPID", "hostIPC"]
          field := fields[_]
          msg := check_violations(input, field)
        }

        check_violations(i, field) = msg {
          i.review.object.spec[field]
          not allowed(i.parameters, field)
          msg := sprintf("Sharing the %v namespace is not allowed: %v", [field, i.review.object.metadata.name])
        }

        allowed(params,"hostIPC") {
          params.allowHostIPC == true
        }

        allowed(params,"hostPID") {
          params.allowHostPID == true
        }
